package com.cgc.venus.server.user.service;

import com.cgc.venus.server.core.base.AbstractBaseService;
import com.cgc.venus.server.core.bean.response.VenusResponseStatus;
import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.core.harbor.HarborService;
import com.cgc.venus.server.core.harbor.client.HarborClient;
import com.cgc.venus.server.core.k8s.inter.K8sNamespaceService;
import com.cgc.venus.server.core.utils.StringUtil;
import com.cgc.venus.server.user.bean.Namespace;
import com.cgc.venus.server.user.bean.Team;
import com.cgc.venus.server.user.bean.namespaceUser;
import com.cgc.venus.server.user.inter.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by 业哥 on 2017/9/11.
 */
@Service
public class TeamServiceImpl extends AbstractBaseService implements TeamService{
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private K8sNamespaceService k8sNamespaceServiceImpl;
    @Autowired
    private HarborService harborServiceImpl;
    @Autowired
    private HarborClient harborClient;
    /**
     * 查询团队信息
     *
     * @param queryKey
     * @param currentUserId 当前用户id
     * @param isSuperAdmin  是否超级管理员
     * @return
     * @throws VenusException
     */
    @Override
    public List<Team> teamQuery(String queryKey, String currentUserId, boolean isSuperAdmin) throws VenusException {
        //=====================业务逻辑=========================
        // 0 主查询表:T_team
        // 1 关联表:  T_namespace     左连接
        // 2 关联表:  T_namespace_uer 左连接
        // 3 条件:queryKey 对应T_team的name_cn/name_en/Described
        //      currentUserId对应T_team的user(如果isSuperAdmin为true 则查询全部忽略本条件)
        //=====================业务逻辑=========================
        //验证
        if (queryKey == null) {
            queryKey = "";
        }
        List<Object> objs = new ArrayList<Object>();
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT ")
                .append(" 	tm.id, ")
                .append(" 	tm.name_cn AS nameCn, ")
                .append(" 	tm.name_en AS nameEn, ")
                .append(" 	tm.Described AS `desc`, ")
                .append(" 	tm.status, ")
                .append(" 	count(DISTINCT ns.id) AS teamNamespaceCount, ")
                .append(" 	count(DISTINCT nsu.id) AS teamUserCount ").append(" FROM ")
                .append(" 	t_team tm ")
                .append(" LEFT JOIN t_namespace ns ON ns.team = tm.id ")
                .append(" LEFT JOIN t_namespace_user nsu ON nsu.namespace = ns.id ")
                .append(" WHERE ")
                .append(" 	1 = 1 ");
        if (!isSuperAdmin) {
            sqlBuf.append(" AND tm.user=? ");
            objs.add(currentUserId);
        }
        sqlBuf.append(" AND ( ")
                .append(" 	tm.name_cn LIKE ? ")
                .append(" 	OR tm.name_en LIKE ? ")
                .append(" 	OR tm.Described LIKE ? ")
                .append(" ) ")
                .append(" GROUP BY ")
                .append(" 	tm.id, ")
                .append(" 	tm.name_en, ")
                .append(" 	tm.name_cn, ")
                .append(" 	tm.Described ");
        objs.add("%" + queryKey + "%");
        objs.add("%" + queryKey + "%");
        objs.add("%" + queryKey + "%");
        List<Team> teams = jdbcTemplate.query(sqlBuf.toString(), new RowMapper<Team>() {
            public Team mapRow(ResultSet rs, int rowNum) throws SQLException {
                Team team = new Team();
                team.setId(rs.getString("id"));
                team.setNameCn(rs.getString("nameCn"));
                team.setNameEn(rs.getString("nameEn"));
                team.setDesc(rs.getString("desc"));
                team.setTeamNamespaceCount(rs.getInt("teamNamespaceCount"));
                team.setTeamUserCount(rs.getInt("teamUserCount"));
                int status=rs.getInt("status");
                String statusStr="";
                if(status==1){
                    statusStr="在用";
                }else{
                    statusStr="停用";
                }
                team.setStatus(statusStr);
                return team;
            }
        }, objs.toArray());
        return teams;
    }

    /**
     * 团队查询
     * @param userId
     * @param isSuperAdmin
     * @return
     * @throws VenusException
     */
    public List teamQuery(String userId,boolean isSuperAdmin)throws VenusException{
        String sql0="SELECT DISTINCT team.id, team.name_cn nameCn FROM t_team team";
        String sql1="SELECT DISTINCT team.id, team.name_cn nameCn FROM t_team team LEFT JOIN t_namespace ns ON ns.team = team.id LEFT JOIN t_namespace_user nsu ON nsu.namespace = ns.id LEFT JOIN t_user u ON u.id = nsu.`user` WHERE u.id = ?";
        if(isSuperAdmin){
            return this.jdbcTemplate.queryForList(sql0);
        }else{
            List<Object> obj=new ArrayList<>();
            obj.add(userId);
            return this.jdbcTemplate.queryForList(sql1,obj.toArray());
        }
    }

    /**
     * 空间查询
     * @param userId
     * @param teamId
     * @param isSuperAdmin
     * @return
     * @throws VenusException
     */
    public List namespaceQuery(String userId,String teamId,boolean isSuperAdmin)throws VenusException{
        String sql0="SELECT DISTINCT ns.id,ns.`name`, ns.kube_name kubeName FROM t_team team LEFT JOIN t_namespace ns ON ns.team = team.id LEFT JOIN t_namespace_user nsu ON nsu.namespace = ns.id LEFT JOIN t_user u ON u.id = nsu.`user` WHERE team.id = ?";
        String sql1="SELECT DISTINCT ns.id,ns.`name`, ns.kube_name kubeName FROM t_team team LEFT JOIN t_namespace ns ON ns.team = team.id LEFT JOIN t_namespace_user nsu ON nsu.namespace = ns.id LEFT JOIN t_user u ON u.id = nsu.`user` WHERE team.id = ? and u.id = ?";
        List<Object> obj=new ArrayList<>();
        if(isSuperAdmin){
            obj.add(teamId);
            return this.jdbcTemplate.queryForList(sql0,obj.toArray());
        }else{
            obj.add(teamId);
            obj.add(userId);
            return this.jdbcTemplate.queryForList(sql1,obj.toArray());
        }
    }


    @Override
    public boolean teamAdd(Team team,String currentUserId) throws VenusException {
        //=====================业务逻辑=========================
        // >>   验证
        // 1    插入一条新记录
        // >>   t_team表插入一条记录
        //=====================业务逻辑=========================
        //验证空异常
        if (team == null) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "team 对象为空!");
        }
        if (StringUtil.isEmpty(currentUserId)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "当前用户信息为空!");
        }
        if (StringUtil.isEmpty(team.getId())) {
            //走插入
            if (StringUtil.isEmpty(team.getNameCn())) {
                throw new VenusException(VenusResponseStatus.NO_CONTENT, "团队名称(中文)为空!");
            }
            if (StringUtil.isEmpty(team.getNameEn())) {
                throw new VenusException(VenusResponseStatus.NO_CONTENT, "团队名称(英文)为空!");
            }
            String sql = "INSERT INTO t_team(id,name_cn,name_en,user,described,status,create_time,last_update_time) VALUES (?,?,?,?,?,?,NOW(),NOW())";
            List<Object> objs = new ArrayList<Object>();
            String newTeamId = StringUtil.getUUID();
            //验证重复异常
            if (validateTeamName(team.getNameCn(), "cn")) {
                throw new VenusException(VenusResponseStatus.DATA_REPEAT, "团队名称(中文)字段重复!");
            }
            if (validateTeamName(team.getNameEn(), "en")) {
                throw new VenusException(VenusResponseStatus.DATA_REPEAT, "团队名称(英文)字段重复!");
            }
            objs.add(newTeamId);
            objs.add(team.getNameCn());
            objs.add(team.getNameEn());
            objs.add(currentUserId);
            objs.add(team.getDesc());
            objs.add(1);//初始状态 1 可用
            int row = jdbcTemplate.update(sql, objs.toArray());
            if (row == 1) {
                return true;
            }else{
                return false;
            }
        }
        return false;
    }
    /**
     * 团队修改
     * @param team
     * @return
     * @throws VenusException
     */
    @Override
    public boolean teamUpdate(Team team) throws VenusException {
        // =====================业务逻辑=========================
        // 验证
        // 更新团队表描述字段
        //=====================业务逻辑=========================
        if (team == null) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "team 对象为空!");
        }
        if (StringUtil.isEmpty(team.getId())) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "当前团队为空,无法做更新!");
        } else {
            //走更新
            String sql = "update t_team team set team.described=? where team.id=?";
            List<Object> objs = new ArrayList<Object>();
            objs.add(team.getDesc());
            objs.add(team.getId());
            int r=this.jdbcTemplate.update(sql,objs.toArray());
            if(r==1){
                return true;
            }
        }
        return false;
    }
    /**
     * 团队停用 根据id
     * @param teamId
     * @return
     * @throws VenusException
     */
    public boolean teamDisableById(String teamId)throws VenusException{
        // =====================业务逻辑=========================
        // 验证
        // 更新团队status自动
        //=====================业务逻辑=========================
        if (StringUtil.isEmpty(teamId)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "团队id为空!");
        }
        //走更新
        String sql = "update t_team team set team.status=0 where team.id=?";
        List<Object> objs = new ArrayList<Object>();
        objs.add(teamId);
        int r=this.jdbcTemplate.update(sql,objs.toArray());
        if(r==1){
            return true;
        }
        return false;
    }
    /**
     * 团队明细查询
     * @param teamId
     * @return
     * @throws VenusException
     */
    @Override
    public Team teamDetailQuery(String teamId) throws VenusException {
        //=====================业务逻辑=========================
        //>> 验证
        //>> 查询team明细信息
        //=====================业务逻辑=========================
        if (StringUtil.isEmpty(teamId)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "团队id为空异常!");
        }
        String sql = "SELECT tm.id, tm.name_cn AS nameCn, tm.name_en AS nameEn, tm.Described AS `desc`,tm.status FROM t_team tm WHERE tm.id = ?";
        List<Object> objs = new ArrayList<Object>();
        objs.add(teamId);
        Team team = this.jdbcTemplate.queryForObject(sql, new RowMapper<Team>() {
            public Team mapRow(ResultSet rs, int rowNum) throws SQLException {
                Team team = new Team();
                team.setId(rs.getString("id"));
                team.setNameCn(rs.getString("nameCn"));
                team.setNameEn(rs.getString("nameEn"));
                team.setDesc(rs.getString("desc"));
                team.setStatus(rs.getString("status"));
                return team;
            }
        }, objs.toArray());
        return team;
    }
    /**
     * 根据id查询命名空间
     *
     * @param teamId
     * @return
     * @throws VenusException
     */
    @Override
    public List<Namespace> namespaceQuery(String teamId) throws VenusException {
        //=====================业务逻辑=========================
        //>> 验证
        //>> 查询team明细信息
        //>> 查询对应namespace信息
        //>> 查询每个namespace对应应用个数
        //=====================业务逻辑=========================
        if (StringUtil.isEmpty(teamId)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "团队id为空异常!");
        }
        String sql = "SELECT ns.id, ns. NAME AS `name`, CASE ns.type WHEN 0 THEN '开发环境' WHEN 1 THEN '测试环境' WHEN 2 THEN '预生产环境' WHEN 3 THEN '生产环境' END AS type, pg.name_cn AS phycicalGroup, pg.id AS physicalGroupId, ns.team AS teamId, 0 AS appCount, ns.kube_name, ns.harbor_project_name, 0 AS imagesCount,CASE ns.`status` WHEN 0 THEN '停用' WHEN 1 THEN '在用' END AS nstatus FROM t_namespace ns LEFT JOIN t_physical_group pg ON pg.id = ns.physical_group WHERE ns.team = ? ";
        List<Object> objs = new ArrayList<Object>();
        objs.add(teamId);
        List<Namespace> namespaces = jdbcTemplate.query(sql, new RowMapper<Namespace>() {
            public Namespace mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new Namespace(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getInt(7), rs.getString(8), rs.getString(9),rs.getInt(10),rs.getString(11));
            }
        }, objs.toArray());
        //查询namespace下面对应应用个数  ---------------未完成
        //查询namespace下面对应镜像个数  ---------------未完成
        return namespaces;
    }
    @Override
    public Boolean namespaceAdd(String teamId, Namespace namespace) throws VenusException {
        //=====================业务逻辑=========================
        //>> 验证  空验证,重复验证
        //>>插入   k8s命名空间建立,harbor镜像库建立,db插入
        //=====================业务逻辑=========================
        if (StringUtil.isEmpty(teamId)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "团队id为空!");
        }
        if (namespace == null) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "命名空间为空!");
        }
        if (StringUtil.isEmpty(namespace.getHarborProjectName())) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像库名称为空!");
        }
        if (StringUtil.isEmpty(namespace.getKubeName())) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "k8s的命名空间为空!");
        }
        if (validateNamespaceName(namespace.getHarborProjectName(), "harbor")) {
            throw new VenusException(VenusResponseStatus.DATA_REPEAT, "镜像库名称重复!");
        }
        if (validateNamespaceName(namespace.getKubeName(), "k8s")) {
            throw new VenusException(VenusResponseStatus.DATA_REPEAT, "k8s的命名空间重复!");
        }
        if (validateNamespaceName(namespace.getName(), "name")) {
            throw new VenusException(VenusResponseStatus.DATA_REPEAT, "命名空间名称重复!");
        }
        //k8s命名空间建立
        boolean b = k8sNamespaceServiceImpl.createNamespace(namespace.getKubeName());
        //harbor镜像库建立
        if (b) {
            boolean har=false;
            try{
                har = harborServiceImpl.projectsCreate(namespace.getHarborProjectName(),false);//建立私有harbor项目
            }catch (VenusException e){
                //回滚k8s命名空间
                k8sNamespaceServiceImpl.deleteNamespace(namespace.getKubeName());
                throw e;
            }
            if (har) {
                int row=0;
                try {
                    //db插入
                    String sql = "INSERT INTO t_namespace(id,name,type,Physical_group,team,kube_name,harbor_project_name,create_time,last_update_time) VALUES (?,?,?,?,?,?,?,NOW(),NOW())";
                    String newNsId_dev = StringUtil.getUUID();
                    List objs = new ArrayList<Object>();
                    objs.add(newNsId_dev);
                    objs.add(namespace.getName());
                    objs.add(namespace.getTypeInt());
                    objs.add(getDefaultPhysicalGroupId());
                    objs.add(teamId);
                    objs.add(namespace.getKubeName());
                    objs.add(namespace.getHarborProjectName());
                    row = jdbcTemplate.update(sql, objs.toArray());
                }catch (Exception e){
                    //回滚k8s命名空间,harbor镜像库名称
                    k8sNamespaceServiceImpl.deleteNamespace(namespace.getKubeName());
                    harborServiceImpl.projectsDelete(namespace.getHarborProjectName());
                    e.printStackTrace();
                    throw new VenusException(VenusResponseStatus.MYSQL_DB_EXCEPTION,"db插入异常!");
                }
                if (row == 0) {
                    //回滚k8s命名空间,harbor镜像库名称
                    k8sNamespaceServiceImpl.deleteNamespace(namespace.getKubeName());
                    harborServiceImpl.projectsDelete(namespace.getHarborProjectName());
                }else{
                    return true;
                }
            } else {
                //回滚k8s命名空间
                k8sNamespaceServiceImpl.deleteNamespace(namespace.getKubeName());
            }
        }
        return false;
    }
    @Override
    public Boolean namespaceDisable(String teamId, String[] namespaceIds) throws VenusException {
        //=====================业务逻辑=========================
        //>> 验证  空验证,
        //>> 走停用
        //=====================业务逻辑=========================
        if (StringUtil.isEmpty(teamId)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "团队id为空!");
        }
        if (namespaceIds==null||namespaceIds.length==0) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "命名空间id为空!");
        }

        //走停用
        String sql = "";
        String[] sqls=new String[namespaceIds.length];
        int i=0;
        for(String namespaceId:namespaceIds){
            sql = "update t_namespace ns set ns.`status`=0 where ns.id='"+namespaceId+"'";
            sqls[i]=sql;
            i++;
        }
        int[] r=this.jdbcTemplate.batchUpdate(sqls);
        if(r.length==namespaceIds.length){
            return true;
        }
        return false;
    }
    /**
     * 命名空间添加用户
     *
     * @param namespaceId
     * @param userId
     * @return
     * @throws VenusException
     */
    @Transactional
    @Override
    public boolean namespaceAddUser(String namespaceId, String[] userId) throws VenusException {
        //=====================业务逻辑=========================
        //验证
        //批量插入
        //=====================业务逻辑=========================
        if (StringUtil.isEmpty(namespaceId)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "命名空间id为空!");
        }
        if (userId == null || userId.length == 0) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "用户id为空!");
        }
        String sql = "INSERT INTO t_namespace_user(id,namespace,user,create_time,last_update_time) VALUES (?,?,?,NOW(),NOW())";
        Object[] obj = null;
        List<Object[]> objs = new ArrayList<Object[]>();
        for (String uId : userId) {
            obj = new Object[3];
            obj[0] = StringUtil.getUUID();
            obj[1] = namespaceId;
            obj[2] = uId;
            objs.add(obj);
        }
        int[] r = jdbcTemplate.batchUpdate(sql, objs);
        if(r.length==userId.length){
            return true;
        }
        return false;
    }
    /**
     * 命名空间删除用户
     *
     * @param namespaceId
     * @param userId
     * @return
     * @throws VenusException
     */
    @Override
    public boolean namespaceRemoveUser(String namespaceId, String[] userId) throws VenusException {
        //=====================业务逻辑=========================
        //验证
        //批量删除
        //=====================业务逻辑=========================
        if (StringUtil.isEmpty(namespaceId)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "命名空间id为空!");
        }
        if (userId == null || userId.length == 0) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "用户id为空!");
        }
        String sql = "delete from t_namespace_user  where namespace=? and user=? ";
        Object[] obj = null;
        List<Object[]> objs = new ArrayList<Object[]>();
        for (String uId : userId) {
            obj = new Object[2];
            obj[0] = namespaceId;
            obj[1] = uId;
            objs.add(obj);
        }
        int[] r = jdbcTemplate.batchUpdate(sql, objs);
        if(r.length==userId.length){
            return true;
        }
        return false;
    }
    /**
     * 命名空间用户(已选)查询
     * @param namespaceId
     * @return
     * @throws VenusException
     */
    @Override
    public List<namespaceUser> namespaceUserSelectQuery(String namespaceId) throws VenusException {
        //=====================业务逻辑=========================
        //>> 验证
        //>> 查询
        //=====================业务逻辑=========================
        if (StringUtil.isEmpty(namespaceId)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "命名空间id为空!");
        }
        String sql = "SELECT u.id, u.`name`, r.`name` FROM t_namespace_user nu LEFT JOIN t_user u ON u.id = nu.`user` LEFT JOIN t_role r ON r.id = u.role WHERE nu.namespace = ?";
        List<Object> objs = new ArrayList<Object>();
        objs.add(namespaceId);
        List<namespaceUser> namespaceUsers = jdbcTemplate.query(sql, new RowMapper<namespaceUser>() {
            public namespaceUser mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new namespaceUser(rs.getString(1), rs.getString(2), rs.getString(3));
            }
        }, objs.toArray());
        return namespaceUsers;
    }
    /**
     * 命名空间用户(备选)查询
     *
     * @param namespaceId
     * @return
     * @throws VenusException
     */
    @Override
    public List namespaceUserUnSelectQuery(String namespaceId) throws VenusException {
        //=====================业务逻辑=========================
        //验证
        //
        //=====================业务逻辑=========================
        if (StringUtil.isEmpty(namespaceId)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "命名空间id为空!");
        }
        String sql = "SELECT u.id, u.`name`, r.`name` role FROM t_user u LEFT JOIN t_role r ON r.id = u.role WHERE r.is_superadmin = 0 AND u.id NOT IN ( SELECT nuser.`user` FROM t_namespace_user nuser WHERE nuser.namespace = ? ) ORDER BY r.`name`";
        Object[] obj = new Object[1];
        obj[0] = namespaceId;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, obj);
        List<Map<String, Object>> listReturn = new ArrayList<Map<String, Object>>();
        String label = "";
        Map<String, Object> mapTmp = null;
        List<Map<String, String>> listTmp = null;
        for (Map<String, Object> map : list) {
            String labelDb = map.get("role").toString();
            if (label.equals("") || !labelDb.equals(label)) {
                label = labelDb;
                mapTmp = new HashMap<String, Object>();
                mapTmp.put("label", label);
                listTmp = new ArrayList<Map<String, String>>();
                Map<String, String> map1Tmp = new HashMap<String, String>();
                map1Tmp.put("value", map.get("id").toString());
                map1Tmp.put("label", map.get("name").toString());
                listTmp.add(map1Tmp);
                mapTmp.put("options", listTmp);
                listReturn.add(mapTmp);
            } else if (labelDb.equals(label)) {
                Map<String, String> map1Tmp = new HashMap<String, String>();
                map1Tmp.put("value", map.get("id").toString());
                map1Tmp.put("label", map.get("name").toString());
                listTmp.add(map1Tmp);
            }
        }
        return listReturn;
    }
    /**
     * 物理分组查询
     * @return
     * @throws VenusException
     */
    @Override
    public List physicalGroupQuery() throws VenusException {
        //=====================业务逻辑=========================
        //
        //=====================业务逻辑=========================
        String sql = "SELECT id, name_cn as name, CASE WHEN type = 0 THEN '共享物理组' WHEN type = 1 THEN '平台专用物理组' WHEN type = 2 THEN '应用系统物理组' END AS type FROM t_physical_group ORDER BY type";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> listReturn = new ArrayList<Map<String, Object>>();
        String label = "";
        Map<String, Object> mapTmp = null;
        List<Map<String, String>> listTmp = null;
        for (Map<String, Object> map : list) {
            String labelDb = map.get("type").toString();
            if (label.equals("") || !labelDb.equals(label)) {
                label = labelDb;
                mapTmp = new HashMap<String, Object>();
                mapTmp.put("label", label);
                listTmp = new ArrayList<Map<String, String>>();
                Map<String, String> map1Tmp = new HashMap<String, String>();
                map1Tmp.put("value", map.get("id").toString());
                map1Tmp.put("label", map.get("name").toString());
                listTmp.add(map1Tmp);
                mapTmp.put("options", listTmp);
                listReturn.add(mapTmp);
            } else if (labelDb.equals(label)) {
                Map<String, String> map1Tmp = new HashMap<String, String>();
                map1Tmp.put("value", map.get("id").toString());
                map1Tmp.put("label", map.get("name").toString());
                listTmp.add(map1Tmp);
            }
        }
        return listReturn;
    }

    /**
     * 团队命名空间物理分组设置
     * @param namespaceIds
     * @param physicalGroupId
     * @return
     * @throws VenusException
     */
    @Override
    public boolean teamNamespacePhysicalGroupSet(String[] namespaceIds, String physicalGroupId) throws VenusException {
        //=====================业务逻辑=========================
        // 验证
        // 对应空间下面有应用在运行中 则不能切换物理组
        // 当前物理分组是否可以分给当前团队的环境.
        // 以上逻辑都没有问题 后做更新操作
        //=====================业务逻辑=========================
        if (namespaceIds==null||namespaceIds.length==0) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "命名空间id为空!");
        }
        if (StringUtil.isEmpty(physicalGroupId)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "物理分组id为空!");
        }

        //验证对应的空间下面是否有在跑应用-----------------------未完成
        //....
        //验证待分配的物理分组是否可以分给当前团队的环境.--------未完成
        //....

        String sql = "update t_namespace ns set ns.physical_group=? where ns.id=? ";
        String[] sqls=new String[namespaceIds.length];
        int i=0;
        for(String namespaceId :namespaceIds){
            sqls[i]="update t_namespace ns set ns.physical_group='"+physicalGroupId+"' where ns.id='"+namespaceId+"' ";
            i++;
        }
        int[] r = jdbcTemplate.batchUpdate(sqls);
        if(r.length==namespaceIds.length){
            return true;
        }
        return false;
    }


    @Override
    public String getDefaultPhysicalGroupId() throws VenusException {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select id from t_physical_group where type=0;");
        if (list == null || list.size() == 0) {
            throw new VenusException(VenusResponseStatus.MYSQL_DB_EXCEPTION, "未查询到默认物理分组!");
        }
        return list.get(0).get("id").toString();
    }



    /**
     * k8s的namespace以及harbor的项目名称唯一性验证
     *
     * @param name
     * @param type (name/k8s/harbor)
     * @return
     * @throws VenusException
     */
    @Override
    public boolean validateNamespaceName(String name, String type) throws VenusException {
        //=====================业务逻辑=========================
        // 如果返回true 表示有重复 否则表示无重复
        //
        //=====================业务逻辑=========================
        if (StringUtil.isEmpty(name)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "需要验证的名称为空!");
        }
        if (StringUtil.isEmpty(type)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "需要验证名称类型为空!");
        }
        String sql = "";
        if (type.equals("k8s")) {
            sql = "select id from t_namespace where kube_name='" + name + "'";
        } else if (type.equals("harbor")) {
            sql = "select id from t_namespace where harbor_project_name='" + name + "'";
        } else if(type.equals("name")) {
            sql = "select id from t_namespace where name='" + name + "'";
        }else{
            return true;
        }
        List r = jdbcTemplate.queryForList(sql);
        if (r != null && r.size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List teamAndNamespaceStats() throws VenusException {
        String sql="SELECT count(*) count FROM t_team UNION ALL SELECT count(*) count FROM t_team WHERE `status` = 0 UNION ALL SELECT count(*) count FROM t_team WHERE `status` = 1 UNION ALL SELECT count(*) count FROM t_namespace UNION ALL SELECT count(*) count FROM t_namespace WHERE `status` = 0 UNION ALL SELECT count(*) count FROM t_namespace WHERE `status` = 1";
        List list=jdbcTemplate.queryForList(sql);
        return list;
    }

    /*
    * 创建harbor秘钥
    * */
    @Override
    public boolean createHarborSecret(String namespace) throws VenusException {
        String url = harborClient.getBaseUrl().replaceAll("http://","");
        url = url.substring(0,url.indexOf("/"));
        String userName = harborClient.getAdminUser();
        String password = harborClient.getAdminPassword();
        return k8sNamespaceServiceImpl.createHarborSecret(url,userName,password,namespace);
    }

    @Override
    public boolean validateTeamName(String name, String type) throws VenusException {
        //=====================业务逻辑=========================
        // 如果返回true 表示有重复 否则表示无重复
        //
        //=====================业务逻辑=========================
        if (StringUtil.isEmpty(name)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "需要验证的名称为空!");
        }
        if (StringUtil.isEmpty(type)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "需要验证名称类型为空!");
        }
        String sql = "";
        if (type.equals("cn")) {
            sql = "select id from t_team where name_cn='" + name + "'";
        } else if (type.equals("en")) {
            sql = "select id from t_team where name_en='" + name + "'";
        } else {
            return true;
        }
        List r = jdbcTemplate.queryForList(sql);
        if (r != null && r.size() > 0) {
            return true;
        }
        return false;
    }
}
